package cn.iocoder.yudao.module.system.controller.admin.examscore;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.system.controller.admin.examscore.vo.*;
import cn.iocoder.yudao.module.system.convert.examscore.ExamScoreConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.examscore.ExamScoreDO;
import cn.iocoder.yudao.module.system.service.examscore.ExamScoreService;
import cn.iocoder.yudao.module.system.service.examscore.ExamScoreServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 学生成绩")
@RestController
@RequestMapping("/system/exam-score")
@Validated
public class ExamScoreController {

    @Resource
    private ExamScoreService examScoreService;

    @PostMapping("/create")
    @Operation(summary = "创建学生成绩")
    @PreAuthorize("@ss.hasPermission('system:exam-score:create')")
    @ApiAccessLog(operateType = CREATE)
    public CommonResult<Long> createExamScore(@Valid @RequestBody ExamScoreCreateReqVO createReqVO) {
        return success(examScoreService.createExamScore(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新学生成绩")
    @PreAuthorize("@ss.hasPermission('system:exam-score:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateExamScore(@Valid @RequestBody ExamScoreUpdateReqVO updateReqVO) {
        examScoreService.updateExamScore(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除学生成绩")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:exam-score:delete')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> deleteExamScore(@RequestParam("id") Long id) {
        examScoreService.deleteExamScore(id);
        return success(true);
    }

    @DeleteMapping("/clear-import")
    @Operation(summary = "清除某次导入的所有成绩数据")
    @Parameter(name = "examId", description = "考试ID", required = true, example = "1")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Integer> clearImportedScores(@RequestParam("examId") Long examId) {
        int deletedCount = examScoreService.deleteExamScoresByExamId(examId);
        return success(deletedCount);
    }
    
    @DeleteMapping("/clear-import-batch")
    @Operation(summary = "按批次清除导入的成绩数据")
    @Parameter(name = "importBatchId", description = "导入批次ID", required = true, example = "BATCH_1699876543210_abc12345")
    @PreAuthorize("@ss.hasPermission('system:exam-score:delete')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Integer> clearImportedScoresByBatch(@RequestParam("importBatchId") String importBatchId) {
        int deletedCount = examScoreService.deleteExamScoresByImportBatchId(importBatchId);
        return success(deletedCount);
    }
    
    @GetMapping("/count-by-batch")
    @Operation(summary = "查询指定批次的成绩数量")
    @Parameter(name = "importBatchId", description = "导入批次ID", required = true, example = "BATCH_1699876543210_abc12345")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<Long> getScoreCountByBatch(@RequestParam("importBatchId") String importBatchId) {
        Long count = examScoreService.getScoreCountByImportBatchId(importBatchId);
        return success(count);
    }

    @GetMapping("/get")
    @Operation(summary = "获得学生成绩")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    @DataPermission
    public CommonResult<ExamScoreRespVO> getExamScore(@RequestParam("id") Long id) {
        ExamScoreRespVO examScore = ((ExamScoreServiceImpl) examScoreService).getExamScoreWithRelations(id);
        return success(examScore);
    }

    @GetMapping("/list")
    @Operation(summary = "获得学生成绩列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<List<ExamScoreRespVO>> getExamScoreList(@RequestParam("ids") Collection<Long> ids) {
        List<ExamScoreRespVO> list = ((ExamScoreServiceImpl) examScoreService).getExamScoreListWithRelations(ids);
        return success(list);
    }

    @GetMapping("/page")
    @Operation(summary = "获得学生成绩分页")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    @DataPermission
    public CommonResult<PageResult<ExamScoreRespVO>> getExamScorePage(@Valid ExamScorePageReqVO pageReqVO) {
        PageResult<ExamScoreRespVO> pageResult = ((ExamScoreServiceImpl) examScoreService).getExamScorePageWithRelations(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出学生成绩 Excel")
    @PreAuthorize("@ss.hasPermission('system:exam-score:export')")
    @DataPermission
    @ApiAccessLog(operateType = EXPORT)
    public void exportExamScoreExcel(@Valid ExamScorePageReqVO exportReqVO,
                                    HttpServletResponse response) throws IOException {
        List<ExamScoreDO> list = examScoreService.getExamScoreList(exportReqVO);
        // 导出 Excel
        List<ExamScoreRespVO> datas = ExamScoreConvert.INSTANCE.convertList(list);
        ExcelUtils.write(response, "学生成绩.xls", "数据", ExamScoreRespVO.class, datas);
    }

    @GetMapping("/list-by-exam")
    @Operation(summary = "根据考试ID获取成绩列表")
    @Parameter(name = "examId", description = "考试ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<List<ExamScoreRespVO>> getExamScoreListByExam(@RequestParam("examId") Long examId) {
        List<ExamScoreRespVO> list = ((ExamScoreServiceImpl) examScoreService).getExamScoreListByExamIdWithRelations(examId);
        return success(list);
    }

    @GetMapping("/list-by-student")
    @Operation(summary = "根据学生ID获取成绩列表")
    @Parameter(name = "studentId", description = "学生ID", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<List<ExamScoreRespVO>> getExamScoreListByStudent(@RequestParam("studentId") Long studentId) {
        List<ExamScoreRespVO> list = ((ExamScoreServiceImpl) examScoreService).getExamScoreListByStudentIdWithRelations(studentId);
        return success(list);
    }


    @PostMapping("/import")
    @Operation(summary = "新高考成绩批量导入（自动创建考试）")
    @PreAuthorize("@ss.hasPermission('system:exam-score:import')")
    @ApiAccessLog(operateType = IMPORT)
    public CommonResult<ExamScoreImportRespVO> importNewExamScores(@RequestParam("file") MultipartFile file) throws IOException {
        return success(examScoreService.importNewExamScores(file));
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得成绩导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 使用模板管理器获取模板数据
        List<ExamScoreImportExcelVO> list = examScoreService.getImportTemplate();
        // 输出
        ExcelUtils.write(response, "成绩导入模板.xls", "成绩列表", ExamScoreImportExcelVO.class, list);
    }

    @GetMapping("/template/source-types")
    @Operation(summary = "获取支持的模板数据源类型")
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<List<String>> getSupportedTemplateSourceTypes() {
        List<String> sourceTypes = examScoreService.getSupportedTemplateSourceTypes();
        return success(sourceTypes);
    }

    @GetMapping("/template/source-type/check")
    @Operation(summary = "检查模板数据源类型是否支持")
    @Parameter(name = "sourceType", description = "数据源类型", required = true)
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<Boolean> checkTemplateSourceType(@RequestParam("sourceType") String sourceType) {
        boolean supported = examScoreService.isTemplateSourceTypeSupported(sourceType);
        return success(supported);
    }

    @PostMapping("/calculate-ranking")
    @Operation(summary = "计算排名")
    @Parameter(name = "examId", description = "考试ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:exam-score:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> calculateRanking(@RequestParam("examId") Long examId) {
        examScoreService.calculateRanking(examId);
        return success(true);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取考试成绩统计信息")
    @Parameter(name = "examId", description = "考试ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<ExamScoreStatisticsRespVO> getExamScoreStatistics(@RequestParam("examId") Long examId) {
        return success(examScoreService.getExamScoreStatistics(examId));
    }

    @GetMapping("/analysis")
    @Operation(summary = "获取成绩分析报告")
    @Parameter(name = "examId", description = "考试ID", required = true)
    @PreAuthorize("@ss.hasPermission('system:exam-score:query')")
    public CommonResult<ExamScoreAnalysisRespVO> getExamScoreAnalysis(@RequestParam("examId") Long examId) {
        return success(examScoreService.getExamScoreAnalysis(examId));
    }

    @GetMapping("/export-equivalent-score")
    @Operation(summary = "导出等效分 Excel")
    @Parameter(name = "examId", description = "考试ID", required = true)
    @DataPermission
    @ApiAccessLog(operateType = EXPORT)
    public void exportEquivalentScoreExcel(@RequestParam("examId") Long examId,
                                           HttpServletResponse response) throws IOException {
        List<ExamScoreEquivalentExportVO> datas = examScoreService.getEquivalentScoreExportList(examId);
        // 导出 Excel
        ExcelUtils.write(response, "等效分数据.xls", "数据", ExamScoreEquivalentExportVO.class, datas);
    }

}
